package com.cheer.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheer.common.Page;
import com.cheer.dao.OaLearnDao;
import com.cheer.dao.OaLearnEntryDao;
import com.cheer.dto.OaLearnAddDTO;
import com.cheer.dto.OaLearnUpdateDTO;
import com.cheer.entity.OaArticleEntity;
import com.cheer.entity.OaLeamPeriodsEntity;
import com.cheer.entity.OaLearnClassEntity;
import com.cheer.entity.OaLearnEntity;
import com.cheer.enums.OaIntegralRuleEnum;
import com.cheer.exception.ServiceException;
import com.cheer.service.*;
import com.cheer.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("oaLearnService")
public class OaLearnServiceImpl extends ServiceImpl<OaLearnDao, OaLearnEntity> implements OaLearnService {

    @Value("${image.url}")
    private String imageUrl;

    @Autowired
    private OaLearnDao oaLearnDao;

    @Autowired
    private OaLearnEntryDao oaLearnEntryDao;

    @Autowired
    private OaLeamPeriodsService oaLeamPeriodsService;

    @Autowired
    private OaIntegralService oaIntegralService;

    @Autowired
    private OaLearnClassService oaLearnClassService;

    @Autowired
    private OaArticleService oaArticleService;

    @Override
    public void add(OaLearnAddDTO learnAddDTO) {
        OaLearnEntity learn = new OaLearnEntity()
                .setName(learnAddDTO.getName())
                .setPid(String.valueOf(learnAddDTO.getPid()))
                .setBqImgUrl(learnAddDTO.getBqImgUrl())
                .setImgUrl(learnAddDTO.getImgUrl())
                .setDescribe(learnAddDTO.getDescribe())
                .setUrl(learnAddDTO.getUrl())
                .setStartTime(String.valueOf((learnAddDTO.getStartTime().getTime() / 1000)))
                .setEndTime(String.valueOf((learnAddDTO.getEndTime().getTime() / 1000)))
                .setAddTime(String.valueOf(DateUtil.currentSeconds()));

        oaLearnDao.insert(learn);
    }

    @Override
    public Page<OaLearnListVO> list(Integer pageNum, Integer pageSize, Integer pid, Integer learnClass) {
        IPage<OaLearnEntity> page = oaLearnDao.selectPageByPid(pageNum, pageSize, pid);

        String path;
        if (learnClass == 0) {
            path = "0,";
        } else {
            OaLearnClassEntity learnClassEntity = oaLearnClassService.getById(learnClass);
            if (learnClassEntity == null) {
                throw new ServiceException("单位不存在");
            }
            path = learnClassEntity.getPath() + learnClass + ",";
        }

        List<Integer> periodIds = page.getRecords().stream()
                .map(oaLearnEntity -> Integer.valueOf(oaLearnEntity.getPid()))
                .collect(Collectors.toList());

        Map<Integer, String> periodMap = CollectionUtils.isEmpty(periodIds) ? new HashMap<>() :
                oaLeamPeriodsService.listByIds(periodIds).stream()
                        .collect(Collectors.toMap(OaLeamPeriodsEntity::getId, OaLeamPeriodsEntity::getName));

        List<OaLearnListVO> learnListVOList = page.getRecords().parallelStream()
                .map(oaLearnEntity -> new OaLearnListVO()
                        .setId(oaLearnEntity.getId())
                        .setName(oaLearnEntity.getName())
                        .setPname(periodMap.get(Integer.valueOf(oaLearnEntity.getPid())))
                        .setTime(DateUtil.format(DateUtil.date(Long.valueOf(oaLearnEntity.getStartTime()) * 1000),
                                "yyyy-MM-dd HH:mm") + "~" +
                                DateUtil.format(DateUtil.date(Long.valueOf(oaLearnEntity.getEndTime()) * 1000),
                                        "yyyy-MM-dd HH:mm"))
                        .setNumber(oaLearnEntryDao
                                .selectLearnNumberLimitTimeByPath(oaLearnEntity.getId(), path, oaLearnEntity.getStartTime(), oaLearnEntity.getEndTime())))
                .collect(Collectors.toList());

        return new Page<>(page, learnListVOList);
    }

    @Override
    public OaLearnInfoVO info(Integer id) {
        OaLearnEntity learn = oaLearnDao.selectById(id);
        if (learn == null) {
            throw new ServiceException("学习不存在");
        }

        OaLearnInfoVO oaLearnInfoVO = new OaLearnInfoVO()
                .setId(learn.getId())
                .setName(learn.getName())
                .setPid(Integer.valueOf(learn.getPid()))
                .setDescribe(learn.getDescribe())
                .setUrl(learn.getUrl())
                .setImgUrl(new ImageVO()
                        .setFullUrl(imageUrl + learn.getImgUrl())
                        .setShortUrl(learn.getImgUrl()))
                .setBqImgUrl(new ImageVO()
                        .setFullUrl(imageUrl + learn.getBqImgUrl())
                        .setShortUrl(learn.getBqImgUrl()))
                .setStartTime(DateUtil.format(DateUtil.date(Long.valueOf(learn.getStartTime()) * 1000),
                        DatePattern.NORM_DATETIME_PATTERN))
                .setEndTime(DateUtil.format(DateUtil.date(Long.valueOf(learn.getEndTime()) * 1000),
                        DatePattern.NORM_DATETIME_PATTERN));

        Integer articleId = learn.getArticleId();
        if (ObjectUtil.isNotNull(articleId)) {
            OaArticleEntity oaArticleEntity = oaArticleService.getById(articleId);
            if(ObjectUtil.isNotNull(oaArticleEntity)){
                oaLearnInfoVO.setArticleId(articleId);
                oaLearnInfoVO.setArticleTitle(oaArticleEntity.getTitle());
            }
        }
        return oaLearnInfoVO;
    }

    @Override
    public void update(OaLearnUpdateDTO learnUpdateDTO) {
        OaLearnEntity learn = oaLearnDao.selectById(learnUpdateDTO.getId());
        if (learn == null) {
            throw new ServiceException("学习不存在");
        }

        OaLearnEntity updateLearn = new OaLearnEntity()
                .setId(learnUpdateDTO.getId())
                .setName(learnUpdateDTO.getName())
                .setPid(String.valueOf(learnUpdateDTO.getPid()))
                .setBqImgUrl(learnUpdateDTO.getBqImgUrl())
                .setImgUrl(learnUpdateDTO.getImgUrl())
                .setDescribe(learnUpdateDTO.getDescribe())
                .setUrl(learnUpdateDTO.getUrl())
                .setArticleId(learnUpdateDTO.getArticleId())
                .setStartTime(String.valueOf((learnUpdateDTO.getStartTime().getTime() / 1000)))
                .setEndTime(String.valueOf((learnUpdateDTO.getEndTime().getTime() / 1000)));

        oaLearnDao.updateById(updateLearn);
    }

    @Override
    public List<SimpleObjectVO> all() {
        List<OaLearnEntity> list = oaLearnDao.selectList();

        List<OaLeamPeriodsEntity> leamPeriodsList = oaLeamPeriodsService.list();
        Map<Integer, String> leamPeriodMap = leamPeriodsList.stream()
                .collect(Collectors.toMap(OaLeamPeriodsEntity::getId, OaLeamPeriodsEntity::getName));

        return list.stream()
                .map(learn -> new SimpleObjectVO()
                        .setId((long) learn.getId())
                        .setName(leamPeriodMap.get(Integer.valueOf(learn.getPid())) + learn.getName()))
                .collect(Collectors.toList());
    }

    @Override
    public List<SimpleObjectVO> sub(Integer pid) {
        List<OaLearnEntity> list = oaLearnDao.selectListByPid(pid);

        return list.stream()
                .map(learn -> new SimpleObjectVO()
                        .setId((long) learn.getId())
                        .setName(learn.getName()))
                .collect(Collectors.toList());
    }

    @Override
    public OaLearnFrontVO listFront() {
        OaLearnFrontVO learnFrontVO = new OaLearnFrontVO();
        learnFrontVO.setIsRelationArticle(false);
        OaLearnEntity learn = oaLearnDao.getFirst();
        Integer articleId = learn.getArticleId();
        if (articleId != null) {
            OaArticleEntity oaArticleEntity = oaArticleService.getById(articleId);
            if (ObjectUtil.isNotNull(oaArticleEntity)) {
                learnFrontVO.setArticleId(oaArticleEntity.getId());
                learnFrontVO.setArticleImageUrl(this.imageUrl + oaArticleEntity.getOneImg());
                learnFrontVO.setIsRelationArticle(true);
            }
        }
        if (learn != null) {
            learnFrontVO.setId(learn.getId());
            learnFrontVO.setImgUrl(imageUrl + learn.getBqImgUrl());
        }

        List<OaLeamPeriodsEntity> periodList = oaLeamPeriodsService.listByOrder();
        learnFrontVO.setPast(periodList.stream()
                .map(oaLeamPeriodsEntity -> new OaLearnPeriodInfoVO()
                        .setId(oaLeamPeriodsEntity.getId())
                        .setName(oaLeamPeriodsEntity.getName())
                        .setDescribe(oaLeamPeriodsEntity.getDescribe()))
                .collect(Collectors.toList()));

        return learnFrontVO;
    }

    @Override
    public OaLearnEntity getFirst() {
        return oaLearnDao.getFirst();
    }

    @Override
    public String getFullName(Integer id) {
        OaLearnEntity learnEntity = oaLearnDao.selectById(id);
        if (learnEntity == null) {
            return "";
        }

        OaLeamPeriodsEntity leamPeriodsEntity = oaLeamPeriodsService.getById(learnEntity.getPid());
        if (leamPeriodsEntity == null) {
            return learnEntity.getName();
        } else {
            return leamPeriodsEntity.getName() + learnEntity.getName();
        }
    }

    @Override
    public List<OaLearnFrontInfoVO> listByPid(Integer pid) {
        List<OaLearnEntity> list = oaLearnDao.selectListByPid(pid);

        return list.stream()
                .map(learn -> new OaLearnFrontInfoVO()
                        .setId(learn.getId())
                        .setBqImgUrl(imageUrl + learn.getImgUrl()))
                .collect(Collectors.toList());
    }

    @Override
    public String enter(Integer id, Integer userId, String openid) {
        String url = oaLearnDao.selectUrlById(id);
        OaLearnEntity firstLearn = getFirst();
        if (Objects.equals(id, firstLearn.getId())) {
            // 本期学习
            oaIntegralService.add(userId, openid, OaIntegralRuleEnum.CURRENT, id);
        }
        // 注释掉往期学习
        return url;
    }

    @Override
    public List<OaLearnEntity> list(long startSecond, long endSecond) {
        return oaLearnDao.list(startSecond, endSecond);
    }
}